package com.starsoft.frame.base.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.starsoft.frame.base.bean.BaseFlexset;
import com.starsoft.frame.base.bean.BaseFlexsetData;
import com.starsoft.frame.base.dao.FlexsetDao;
import com.starsoft.frame.base.dao.FlexsetDataDao;
import com.starsoft.frame.util.StringUtil;

@Service
public class FlexsetService {

	public static Logger logger = LoggerFactory.getLogger(FlexsetService.class);
	
	@Autowired
	FlexsetDao flexsetDao;

	@Autowired
	FlexsetDataDao flexsetDataDao;

	public Map<String, List<?>> getFlexsetValues(String flexsetCodes) {
		String[] codes = StringUtil.split2Array(flexsetCodes, ",");
		Map<String, List<?>> re = new HashMap<>();
		for (String code : codes) {
			re.put(code, this.getFlexsetValue(code));
		}
		return re;
	}

	public List<?> getFlexsetValue(String flexsetCode) {
		BaseFlexset flexset = flexsetDao.get(flexsetCode);
		if(flexset==null){
			throw new RuntimeException("Wrong flexsetCode "+flexsetCode);
		}
		if ("const".equals(flexset.getType())) {
			return flexsetDataDao.getFlexsetData(flexsetCode);
		} else if("table".equals(flexset.getType())){
			String sql = flexset.getQuerySql();
			return flexsetDataDao.findBySql(sql);
		} else {
			return null;
		}
	}
	
	public String getFlexsetValue(String flexsetCode, String code) {
		BaseFlexset flexset = flexsetDao.get(flexsetCode);
		if ("const".equals(flexset.getType())) {
			return flexsetDataDao.getFlexsetValue(flexsetCode, code);
		} else if ("table".equals(flexset.getType())) {
			String sql = flexset.getQuerySql();
			sql = "select * from (" + sql + ") where code=?0";
			List<Map<String, Object>> resultList = flexsetDataDao.findBySql(sql, code);
			if (resultList.isEmpty()) {
				return (String) resultList.get(0).get("name");
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Cacheable(value="serviceCache")
	public String codeConvertFrom(String flexCode, String code, String from) {
		List<BaseFlexsetData> datas = flexsetDataDao.getExFlexsetData(flexCode, from);
		for(BaseFlexsetData data : datas){
			if(data.getExvalue().equals(code)){
				return data.getCode();
			}
		}
		throw new RuntimeException("Can't convert "+code);
	}

	@Cacheable(value="serviceCache")
	public String codeConvertTo(String flexCode, String code, String to) {
		List<BaseFlexsetData> datas = flexsetDataDao.getExFlexsetData(flexCode, to);
		for(BaseFlexsetData data : datas){
			if(data.getCode().equals(code)){
				return data.getExvalue();
			}
		}
		throw new RuntimeException("Can't convert "+code);
	}
}
